from app import app, db
from models import User
from flask import request, url_for, redirect, flash, render_template
from flask_login import login_user, logout_user,current_user
import forms

# 后端处理文件


@app.route('/', methods=['GET', 'POST'])
def index():
    print(current_user.is_authenticated)
    print(current_user.is_anonymous)
    return render_template('index.html')

# -----------------------------------------------


@app.route('/user/login', methods=['GET', 'POST'])
def login():  # 登录
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    form = forms.LoginForm()
    if request.method == 'POST':
        userID = request.form.get('userID')
        password = request.form.get('password')

        if not userID or not password:
            flash('请输入')
            return redirect(url_for('login'))

        user = User.query.filter_by(userID=userID).first()
        if user is None:
            flash('用户名错误')
            return redirect(url_for('login'))
        if not user.validate_password(password):
            flash('密码错误')
            return redirect(url_for('login'))
        flash('登录成功')
        login_user(user,remember=True)
        print(current_user)
        return redirect(url_for('index'))
    return render_template('login.html', form=form)


@app.route('/logging', methods=['GET', 'POST'])
def logging():  # 注册
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    if request.method == 'POST':
        userID = request.form.get('userID')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')
        phone = request.form.get('phone')
        user_phone = User.query.filter_by(phone=phone).first()
        if user_phone is not None:
            flash('手机号已被注册')
            return redirect(url_for('logging'))
        email = request.form.get('email')
        user_email = User.query.filter_by(email=email).first()
        if user_email is not None:
            flash('邮箱已被注册')
            return redirect(url_for('logging'))
        if password1 != password2:
            flash('两次输入的密码不同')
            return redirect(url_for('logging'))
        user = User.query.filter_by(userID=userID).first()
        if user is not None:
            flash('用户已注册')
            return redirect(url_for('login'))
        new_user = User(userID=userID, password=User.set_password(password1), phone=phone, email=email)
        db.session.add(new_user)
        db.session.commit()
        flash('注册成功')
        login_user(new_user)
        return redirect(url_for('index'))
    return render_template('logging.html')


@app.route('/logout')
def logout():  # 登出
    logout_user()
    flash('登出')
    return redirect(url_for('index'))